const mongoose = require('mongoose');
const Cate = require('../models/cate-models');
//新增
exports.create = function(req, res, next) {
        const cate = new Cate(req.body);
        cate.save().then((data) => {
            res.json(data);
        });
    }
    //修改
exports.update = function(req, res, next) {
        const id = req.params.id;
        Cate.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => { //new:false 如果通过id没找到就重新创建一个
            res.json(data); //返回的是修改之前的数据
        })
    }
    //批量删除
exports.removes = function(req, res, next) {
        var ids = req.body.ids.split(',');
        if (ids.length > 0) {
            Cate.remove({ _id: { $in: ids } }).then(data => {
                res.json({ 'message': 'delete ok', status: 200 })
            })
        }
        console.log(ids);
    }
    //查询
exports.list = function(req, res, next) {
        var type = req.params.type;
        Cate.find({ type: type }).then(data => {
            // console.log(data);
            var rpTree = reverseTree(data, null);
            res.json(rpTree);
        })
    }
    //获取单条数据
exports.getData = function(req, res, next) {
    var id = req.params.id;
    Cate.findById(id).then(data => {
        res.json(data);
    })
}


function reverseTree(data, pid) {
    var result = [],
        temp;
    var data = JSON.parse(JSON.stringify(data)); //把数据模型对象转化成js对象
    for (var i in data) {
        if (data[i].parentId == pid) {
            result.push(data[i]);
            temp = reverseTree(data, data[i]._id);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;
}